//
//  CollectView.swift
//  AliBaiChuan
//
//  Created by 郑东喜 on 2017/2/22.
//  Copyright © 2017年 郑东喜. All rights reserved.
//  九宫格

import UIKit

class CollectView: UIViewController {
    
    var _window             :UIWindow!
    
    //表格
    fileprivate lazy var tableView: UITableView = {
        let t : UITableView = UITableView.init(frame: self.view.bounds, style: .plain);
        t.delegate = self;
        t.dataSource = self;
        return t
    }()
    
    //数据源
    fileprivate lazy var dataSOuece: NSMutableArray = {
        let u : NSMutableArray = ["阿萨斯","ssasa","asasas"]
        return u
    }()
    
    
    let cellIdentifier = "CoclumnCollectionViewCell"
    
    ///行间距
    fileprivate let margin : CGFloat = 10
    
    fileprivate let SPACE : CGFloat = 10
    
    
    let headTwo = "ColumnReusableViewTwo"
    
    
    lazy var btnn: UIButton = {
        let btn : UIButton = UIButton.init(frame: CGRect.init(x: SW * 0.8, y: SH * 0.8, width: 50, height: 50))
        
        btn.addTarget(self, action: #selector(chageLayout(sender:)), for: .touchUpInside)
        btn.backgroundColor = .red
        
        btn.backgroundColor = .red
        
//        btn.isHidden = true
//        btn.alpha = 0
        return btn
    }()
    
    //数量
    fileprivate let count : Int = 2

    //九宫盒
    lazy var collect: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.vertical
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        
        
        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        
        
        collectionView.backgroundColor = UIColor.gray
        collectionView.dataSource = self
        collectionView.delegate = self
        
        collectionView.alwaysBounceVertical = true

        //注册cell
        collectionView.register(CollectCell.classForCoder(), forCellWithReuseIdentifier: self.cellIdentifier);
        
//        collectionView.register(CollectCell.self,
//                                     forCellWithReuseIdentifier: self.cellIdentifier)
        
        //注册头部尾部cell
        collectionView.register(CollReuseV.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: self.headTwo);
        
        return collectionView
    }()


    
    lazy var dataSource: NSMutableArray = {
        let a : NSMutableArray = ["啊","没后","啊asddadasdsadsadasdasdadasdasdadasdasdasdsadas","123没后","456啊","没3321后","啊13213","没sfff后","啊adsdsd","没asdsadsadsa后","啊1232321","没ddsfdsfd后","啊","没后","啊","没后","qsdd啊","没asdsadsad后","adasasdsa啊","没df12121后","asdsdsad啊","没dsadsdsa后","asddsdsad啊","没qewqewqewq后"]
        return a
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        title = "商品"

        view.addSubview(self.collect)
        
        view.addSubview(btnn)
        
        self.view.insertSubview(btnn, aboveSubview: self.view)
    }
    
}

// MARK:- UICollectionViewDelegate,UICollectionViewDataSource
extension CollectView : UICollectionViewDelegate,UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        // 获取设计的单元格，不需要再动态添加界面元素
        let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: self.cellIdentifier, for: indexPath) as? CollectCell
        
        cell?.layer.borderWidth = 1

        cell?.shopName.text = self.dataSource[indexPath.row] as? String

        return cell!
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 1
        default:
            return dataSource.count
        }
    
    }
}

// MARK:- UICollectionViewDelegateFlowLayout
extension CollectView : UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let _width : CGFloat = (UIScreen.main.bounds.width - 3 * self.margin) / CGFloat(self.count)
        
        return CGSize.init(width: _width, height: _width * 1.5)
    
    }

    //collectionCell的间距上左下右
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: SPACE, left: SPACE, bottom: SPACE, right: SPACE)
    }
    
    
    //表头表位复用
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        
        var reuseView : CollReuseV?
        
        print("\((#file as NSString).lastPathComponent):(\(#line))\n")
        
        if indexPath.section == 0 {
            if kind == UICollectionElementKindSectionHeader {
                reuseView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headTwo, for: indexPath) as? CollReuseV
                print("\((#file as NSString).lastPathComponent):(\(#line))\n")
            }
        } else {
            reuseView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headTwo, for: indexPath) as? CollReuseV
        }

        return reuseView!
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: SW, height: 30.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: SW, height: 0.0)
    }
}


// MARK:- 改变布局
extension CollectView {
    @objc fileprivate func chageLayout(sender : UIButton) -> Void {
        
        sender.isSelected = !sender.isSelected
        
        if sender.isSelected {
            
            self.collect.removeFromSuperview()
            
            
            self.view.insertSubview(self.tableView, belowSubview: self.btnn)
        } else {
            self.tableView.removeFromSuperview()
            
            self.view.insertSubview(self.collect, belowSubview: self.btnn)
        }
    }
}

// MARK:- UITableViewDelegate,UITableViewDataSource
extension CollectView : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as? LineCell
        
        if cell == nil {
            cell = LineCell(style: .default, reuseIdentifier: "cellID")
        }
        
        cell?.textLabel?.text = self.dataSource[indexPath.row] as? String
        return cell!
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 45
    }
}


extension CollectView : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 100 {
            self.btnn.isHidden = false
        } else {
            self.btnn.isHidden = true
        }
    }
    
    fileprivate func dismiss() -> Void {
        _window = nil
    }
}

